//
//  XGLoginViewModel.swift
//  TodayNews
//
//  Created by monkey on 2020/4/12.
//  Copyright © 2020 itcast. All rights reserved.
//

import LeanCloud

class XGLoginViewModel: XGLeanCloudErrorReason
{
    /// 用户登录
    /// - Parameters:
    ///   - userName: 用户名
    ///   - password: 密码
    ///   - completion: 完成回调
    func login(userName: String, password: String, completion: @escaping (Bool, String?) -> Void) -> Void
    {
        XGUserModel.logIn(username: userName, password: password) { (result) in
            if result.isSuccess {
                XGUserAccountManager.shared.saveUserAccount(userModel: result.object)
                completion(true, nil)
            } else {
                completion(false, self.reasonFromErrorCode(code: result.error?.code ?? 0) ?? "登录失败!")
            }
        }
    }
    
    func loginIn(platform :UMSocialPlatformType, completion: @escaping (Bool) -> Void) -> Void
    {
        UMSocialManager.default()?.getUserInfo(with: platform, currentViewController: nil, completion: { (result, error) in
            guard let result = result as? UMSocialUserInfoResponse else {
                completion(false)
                return
            }
            XGUserAccountManager.shared.saveUserAccount(userModel: result)
            completion(true)
        })
    }
}
